package com.ilibrary.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;

import com.ilibrary.base.MyAjaxAction;
import com.ilibrary.base.MyBaseVO;
import com.ilibrary.constants.MyConstants;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.service.AdminService;
import com.ilibrary.utils.MD5Utils;
import com.ilibrary.utils.MyColumnIndicator;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.AdminVO;

public class DoChangePwdAdminAction extends MyAjaxAction {

	private AdminService adminService;
	
	public AdminService getAdminService() {
		return adminService;
	}
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	@Override
	protected JSONObject doExecute(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		JSONObject jo = new JSONObject();
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		
        AdminVO adminVO = (AdminVO)request.getSession().getAttribute(MyConstants.ILIBRARY_LOGIN_ADMIN);
        if(adminVO == null) {
        	jo.put("success", false);
        	jo.put("msg", MyMsgConstants.LOGIN_SESSION_INVALID);
          	return jo;
        }
        if(StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd)){
        	jo.put("success", false);
        	jo.put("msg", MyMsgConstants.UPDATE_EXCEPTION);
        	return jo;
        }
        ResultDto<AdminVO> resultDto = adminService.findById(adminVO.getAdminId());
        if(resultDto.isSuccess()) {
            AdminVO orgAdminVO = resultDto.getFirstResult();
    		if(!orgAdminVO.getAdminPwd().equals(MD5Utils.generateForPassword(oldPwd))) {
    			jo.put("success", false);
    			jo.put("msg", MyMsgConstants.USER_ID_PWD_INVALID);
    			return jo;
    		}else {
    			orgAdminVO.setAdminPwd(MD5Utils.generateForPassword(newPwd));
    			ResultDto<MyBaseVO> resultDto2 = adminService.update(orgAdminVO);
    			if (resultDto2.isSuccess()) {
					jo.put("success", true);
					return jo;
				}else {
		        	jo.put("success", false);
		        	jo.put("msg", resultDto2.getMsg());
		        	return jo;
				}
    		}
        }else {
        	jo.put("success", false);
        	jo.put("msg", resultDto.getMsg());
        	return jo;
        }
	}

}
